﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;


public class BasePage : System.Web.UI.Page
{
    protected override void SavePageStateToPersistenceMedium(object pageViewState)
    {
        #region 方法一
        //LosFormatter losformatter = new LosFormatter();
        //StringWriter sw = new StringWriter();
        //losformatter.Serialize(sw, pageViewState);
        //string viewStateString = sw.ToString();
        //byte[] b = Convert.FromBase64String(viewStateString);
        //b = ViewStateCompression.Compress(b);
        //ClientScript.RegisterHiddenField( "__CUSTOMVIEWSTATE", Convert.ToBase64String(b) );
        ////
        //// 兼容ASP.NET AJAX 的ViewState
        //ScriptManager.RegisterHiddenField( this, "__CUSTOMVIEWSTATE", Convert.ToBase64String( b ) );
        #endregion

        MemoryStream ms = new MemoryStream();
        LosFormatter m_formatter = new LosFormatter();
        m_formatter.Serialize(ms, pageViewState);
        ms.Position = 0;
        StreamReader sr = new StreamReader(ms);
        string viewStateString = sr.ReadToEnd();
        byte[] ViewStateBytes = Convert.FromBase64String(viewStateString);
        ViewStateBytes = ViewStateCompression.Compress(ViewStateBytes);
        Session["ViewState"] = Convert.ToBase64String(ViewStateBytes);
        ms.Close();      
    }

    // 序列化ViewState
    protected override object LoadPageStateFromPersistenceMedium()
    {
        #region 方法一
        //string custState = Request.Form["__CUSTOMVIEWSTATE"];
        //byte[] b = Convert.FromBase64String(custState);
        //b = ViewStateCompression.Decompress(b);
        //LosFormatter losformatter = new LosFormatter();
        //return losformatter.Deserialize(Convert.ToBase64String(b));
        #endregion
        
        string m_viewState = (string)Session["ViewState"];
        byte[] ViewStateBytes = Convert.FromBase64String(m_viewState);
        ViewStateBytes = ViewStateCompression.Decompress(ViewStateBytes);
        LosFormatter m_formatter = new LosFormatter();
        //object viewStateBag = m_formatter.Deserialize(Convert.ToBase64String(ViewStateBytes));
        return m_formatter.Deserialize(Convert.ToBase64String(ViewStateBytes));
    }
}

